<template>
    <el-dialog
    append-to-body
    :close-on-click-modal="false"
    :close-on-press-escape="false"
     width="80%"
     top="2vh"
    :title="title"
    :before-close="close"
    v-if="showDialog"
    :visible.sync="showDialog">
    <div class="wp-panel">
      <div class="wp-panel__form">
        <el-form :model="productOutInfo" label-width="120px"  ref="productEntryForm" :rules="rules">
          <el-row>
            <el-col :span="12">
              <el-form-item label="出库单号" prop="stockDetailNo" :rules="[{ required: policy==2, message: '不能为空', trigger: 'blur' }]">
            <el-radio v-model="policy" label="1" border size="mini">自动生成</el-radio>
            <el-radio v-model="policy" label="2" border size="mini">手动输入</el-radio>
            <el-input
              v-if="policy==2"
              class="wp-form-280"
              v-model.trim="productOutInfo.stockDetailNo"
              placeholder="出库单号"
              clearable
            ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出库类型" prop="operationSubType">
                <el-select
                  class="wp-form-280"
                  v-model="productOutInfo.operationSubType"
                  placeholder="出库类型"
                >
                 <el-option v-for="item in operationSubTypes" :key="item.value" :value="item.value" :label="item.label"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item  label="出库时间" prop="stockDate">
                <el-date-picker
                   style="width:280px"
                  v-model="productOutInfo.stockDate"
                  value-format="yyyy-MM-dd"
                  placeholder="出库时间"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="关联订单号" v-if="sourceType!=='default'" prop="remark">
                <el-input
                  class="wp-form-280"   :disabled="isDisabled"
                  v-model="productOutInfo.associateOrder"
                  placeholder="关联订单号"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="wp-panel__talbe">
        <div class="header"  v-if="sourceType=='default'">
          <el-button type="warning" icon="el-icon-plus" @click.native="onOpenPanel">添加产品</el-button>
        </div>
        <el-table
          stripe
          ref="productListTable"
          :data="productList"
          :key="talbekey"
          :row-class-name="tableRowClassName"
          @cell-click="cellclick"
        >
          <el-table-column v-if="!isDisabled" type="selection" width="50"></el-table-column>
          <el-table-column
            width="120"
            label="产品名称"
            prop="productName"
            show-overflow-tooltip
          ></el-table-column>
        <el-table-column  label="产品类型" prop="productType" show-overflow-tooltip :formatter="formatterProductType"></el-table-column>
          <el-table-column
            label="产品型号"
            prop="productModel"
            show-overflow-tooltip
          ></el-table-column>
        <el-table-column
          label="所属仓库"
          prop="warehouseName"
        ></el-table-column>
          <el-table-column width="100"  label="可出库数量" prop="availableNum"></el-table-column>
           <el-table-column label="出库价格(元)" :width="sourceType=='default'? 150:100" prop="price">
            <template slot-scope="scope">
              <el-input-number
                v-if="sourceType=='default'"
                size="mini"
                :min="1"
                v-model="scope.row.price"
              ></el-input-number>
              <span v-else>
                {{scope.row.price * (scope.row.discountRate?scope.row.discountRate:1)}}
              </span>
            </template>
          </el-table-column>
          <el-table-column width="150" label="出库数量" prop="productNum">
            <template slot-scope="scope">
              <el-input-number
                v-if="!isDisabled"
                size="mini"
                :min="1"
                :max="sourceType=='default'?scope.row.availableNum:scope.row.lockedNum"
                v-model="scope.row.productNum"
              ></el-input-number>
              <span v-else>{{ scope.row.productNum }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" show-overflow-tooltip prop="remark">
            <template slot-scope="scope">
              <el-input
                v-if="remarkIsActive(scope.row)"
                maxlength="100"
                size="mini"
                :ref="scope.row.id + scope.$index"
                @blur="remarkBlur(scope.row)"
                v-model="scope.row.remark"
              ></el-input>
              <el-tooltip v-else :content="scope.row.remark" placement="top">
                <span>{{ scope.row.remark }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="操作" v-if="sourceType=='default'" align="center">
            <template slot-scope="scope">
              <el-link
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="wp-dialog-footer">
      <el-button @click.native="close">取 消</el-button>
      <el-button type="success" @click.native="save('productEntryForm')">确 定</el-button>
    </div>
    <Drawer v-if="sourceType=='default'" ref="outProductDrawer" width="60%">
        <Product-stock-search :plist.sync="productList"/>
    </Drawer>
    </el-dialog>

</template>

<script>
import Drawer from '@/components/Drawer'
import Common from '@/views/mixins/common'
import stock from '@/api/eims/stockAPI'
import salesOrder from '@/api/eims/sales/salesOrderAPI'
import ProductStockSearch from '../productStockSearch'
export default {
  props: {
    visible: {type: Boolean, default: false},
    associateOrder: String,
    sourceType: {type: String, default: 'default'},
    operationSubTypes: {type: Array,
      default: () => {
        return [
          {value: 20, label: '销售单出库'},
          {value: 21, label: '采购退货出库'},
          {value: 22, label: '调拨出库'},
          {value: 23, label: '人工出库'}
        ]
      }}
  },
  mixins: [Common],
  components: {Drawer, ProductStockSearch},
  watch: {
    showDialog (nVal) {
      this.$emit('update:visible', nVal)
    },
    productList (nVal) {
      this.reloadList()
    },
    operationSubTypes (nVal) {
      this.productOutInfo['operationSubType'] = nVal[0].value
    }
  },
  created () {
    this.init()
  },
  data () {
    return {
      title: '新建出库单',
      showDialog: this.visible,
      productOutInfo: {},
      productList: [],
      activeRemarks: [],
      policy: '1',
      talbekey: '',
      isDisabled: false,
      rules: {
        operationSubType: [{ required: true, message: '不能为空', trigger: 'blur' }],
        stockDate: [{ required: true, message: '不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    init () {
      this.productOutInfo = {}
      this.policy = '1'
      if (this.operationSubTypes) {
        this.productOutInfo.operationSubType = this.operationSubTypes[0].value
      }
      this.isDisabled = this.associateOrder !== undefined && this.associateOrder !== null
      this.productList = []
      if (this.isDisabled) {
        this.productOutInfo.associateOrder = this.associateOrder
        //  查询订单锁定信息
        this.getSalesOrderProductLockedInfo(this.associateOrder)
      }
    },
    reloadList () {
      this.talbekey = Math.random()
    },
    close () {
      this.showDialog = false
    },
    getSalesOrderProductLockedInfo (associateOrder) {
      this.requestOption(salesOrder.getSalesOrderProductLockedListAPI, associateOrder, res => {
        if (res.data) {
          this.productList = res.data.map(v => {
            v.availableNum = v.lockedNum
            v.productNum = v.lockedNum
            return v
          })
        }
      })
    },
    save (formName) {
      if (this.checkFormData(formName)) {
        let plist = []
        if (this.isDisabled) {
          plist = [...this.productList]
        } else {
          const productList = this.$refs.productListTable.selection
          for (let i = 0; i < productList.length; i++) {
            if (!productList[i].price || productList[i].price === undefined) {
              this.$msgBox.error('出库价格不能为空')
              return
            }
            if (!productList[i].productNum || productList[i].productNum === undefined) {
              this.$msgBox.error('出库数量不能为空')
              return
            }
            const product = {}
            product.productCode = productList[i].productCode
            product.productName = productList[i].productName
            product.productModel = productList[i].productModel
            product.productType = productList[i].productType
            product.unit = productList[i].unit
            product.productNum = productList[i].productNum
            product.price = productList[i].price
            product.warehouseCode = productList[i].warehouseCode
            product.remark = productList[i].remark
            plist.push(product)
          }
        }
        if (!plist || plist.length <= 0) {
          this.$msgBox.error('选择出库产品')
          return
        }
        this.productOutInfo.operationType = 2
        this.productOutInfo.productList = plist
        this.$msgBox.confirm('确认产品出库', () => {
          stock.addProductStorageAPI(this.productOutInfo).then(res => {
            if (res.code === 0) {
              this.close()
              this.$emit('afterSave', res)
            }
          })
        })
      }
    },
    onOpenPanel () {
      this.$refs.outProductDrawer.show()
    },
    tableRowClassName ({ row, rowIndex }) {
      row.index = rowIndex
      return ''
    },
    remarkIsActive (row) {
      return this.activeRemarks.includes(row.id)
    },
    remarkBlur (row) {
      this.activeRemarks = this.activeRemarks.filter((item) => {
        return item !== row.id
      })
    },
    cellclick (row, column, cell, event) {
      if (column.property === 'remark') {
        if (!this.activeRemarks.includes(row.productCode)) {
          this.activeRemarks.push(row.id)
        }
        this.$nextTick(() => {
          this.$refs[`${row.id + row.index}`].focus()
        })
      }
    },
    handleDelete (index, row) {
      this.$msgBox.confirm(
        '确认删除产品' + (row.productName || '') + '?',
        () => {
          this.productList.splice(index, 1)
        }
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.wp-panel {
  height: 450px;
  overflow: auto;
  padding: 10px;
}
.wp-panel__talbe {
  text-align: right;
  .header {
    margin-bottom: 5px;
  }
}
</style>
